#CaliforniWay Plugin
import re,sys,urllib,urllib2,urlparse,base64
import xbmcgui, xbmcplugin, xbmcaddon
from BeautifulSoup import BeautifulSoup, SoupStrainer

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
try:
    from urlparse import parse_qs
except ImportError:
    #python 2.4 compatibility
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs
args = urlparse.parse_qs(sys.argv[2][1:])

#PLUGIN CONSTANTS
plugin_id = 'plugin.video.californiway'
addon = xbmcaddon.Addon(id=plugin_id)

#COMMON PLUGIN FUNCTIONS
#subfolder url link
def build_url(query):
    return base_url + '?' + urllib.urlencode(query)

#chrome web browser act a like
useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'

def getURL(url):
        print '>>>>>CaliforniWay Plugin :: getURL :: url = '+url
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', useragent)
            response = urllib2.urlopen(req)
            link=response.read()
            response.close()
        except urllib2.HTTPError, error:
            print 'Error reason: ', error
            return error.read()
        else:
            return link

mode = args.get('mode', None)
 
if mode is None:
    vidlist = 'https://californiway.googlecode.com/svn/trunk/plugin.video.californiway/resources/media/vidlist.xml'
    data = getURL(vidlist)
    soup = BeautifulSoup(data)
    videolist = soup.findAll('vid')
    for video in videolist:
        name = base64.b64decode(video['name'])
        mode = base64.b64decode(video['mode'])
        videourl = base64.b64decode(video['url'])
        thumb = base64.b64decode(video['thumb'])
        url = build_url({'mode': mode, 'foldername': name, 'url': videourl, 'thumb': thumb})
        li = xbmcgui.ListItem(name, iconImage=thumb)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'pl':
    vidtitle = args['foldername'][0]
    url = args['url'][0]
    data = getURL(url)
    match=re.compile('{file:"(.+?)",label:"(.+?)"}').findall(data)
    for vidurl,quality in match:
        li = xbmcgui.ListItem(quality, iconImage='DefaultVideo.png')
        li.setInfo('video', { 'title': vidtitle })
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=vidurl, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'mt':
    vidtitle = args['foldername'][0]
    url = args['url'][0]
    data = getURL(url)
    vidlink = SoupStrainer('video')
    soup = BeautifulSoup(data, parseOnlyThese=vidlink)
    videolist = soup.findAll('source')
    for source in videolist:
        quality = source['data-res']
        vidurl = source['src']
        li = xbmcgui.ListItem(quality + 'p', iconImage='DefaultVideo.png')
        li.setInfo('video', { 'title': vidtitle })
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=vidurl, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)
        
